package rpt

import (
	"bytes"
	"context"
	"encoding/json"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/tpl"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/tool"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/go-log"
	"io"
	"time"
)

func HandleRptFile(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(time.Second * 10):
			_handleRptFile()
		}
	}
}
func _handleRptFile() {
	var err error
	var list []db.AmazonRpt
	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonRpt)).
		Filter("Status", db.RptStatusDownloaded).
		Limit(1).All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		//log.Info("no rpt")
		return
	}
	var rpt = list[0]
	err = _persistentFile(rpt)
	if err != nil {
		log.Info("persistent data failed")
		log.Info(err)
		savePersistenceResult(rpt, db.RptStatusFail)
		return
	}
	savePersistenceResult(rpt, db.RptStatusClosed)
}

func _persistentFile(rpt db.AmazonRpt) (err error) {

	var file = rpt.GetTempFileName()
	log.Info("persistent file %s", file)
	var resp []map[string]any
	err = tool.ReadGzip(file, func(reader io.Reader) (e error) {
		var buf = bytes.NewBuffer(make([]byte, 0))
		_, e = io.Copy(buf, reader)
		if e != nil {
			return
		}
		e = json.Unmarshal(buf.Bytes(), &resp)
		return
	})
	if err != nil {
		log.Info(err)
		return
	}
	if len(resp) == 0 {
		log.Info("no data in rpt file")
		return
	}
	template, err := tpl.GetTpl(rpt.RptTemplateId)
	if err != nil {
		log.Info("unknown rpt template: %s", rpt.RptTemplateId)
		log.Info(err)
		// TODO
		return
	}
	var table = template.GetTplName()
	handleTable(table, template.Columns...)

	var dataBuf []map[string]any
	for i, item := range resp {
		//if i > 0 {
		//	break
		//}
		if i%10 == 0 {
			if len(dataBuf) > 0 {
				err = db.SaveData(dataBuf, table, template.Columns...)
				if err != nil {
					log.Info(err)
					return
				}
				dataBuf = []map[string]any{}
			}
		}
		dataBuf = append(dataBuf, item)
		log.Info("%v", item)
	}
	if len(dataBuf) > 0 {
		err = db.SaveData(dataBuf, table, template.Columns...)
		if err != nil {
			log.Info(err)
			return
		}
	}
	return
}

func handleTable(name string, fields ...db.Column) {

	err := db.CreateTable(name, fields...)
	if err != nil {
		log.Info(err)
		return
	}
}

func savePersistenceResult(rpt db.AmazonRpt, status int) {
	rpt.Status = status
	_, err := app.GetOrm().Context.Update(&rpt)
	if err != nil {
		log.Info(err)
		return
	}
	log.Info("close rpt success")
}
